import numpy as np
import time
from io import StringIO
import pyecharts.options as opts
from pyecharts.charts import Line
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
import sorts
import doc_control


def runTest(algo,testTime=10):
    consumedTime = []
    testSet = generate(testTime+1)
    for i in range(1,testTime+1):
        startTime = time.time()
        algo.algory(algo,collection= testSet[i])
        stopTime = time.time()
        consumedTime.append((stopTime - startTime)*1000)
    return consumedTime

def generate(testTime=10):
    testSet=[]
    for i in range(testTime):
        randSet=np.random.randn(1000*i)
        childSet=[]
        for i in randSet:
            childSet.append(i)
        testSet.append(childSet)
    return testSet

def png_maker(consumedTime,sort_name):
    number_items_list = ["1000", "2000", "3000", "4000", "5000", "6000", "7000", "8000", "9000", "10000"]
    png_name="./png/"+sort_name+".png"

    line = Line()
    line.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    line.set_global_opts(
        axispointer_opts=opts.AxisOpts(type_='value'),
        xaxis_opts=opts.AxisOpts(name="Number of Items",
                                 name_gap=30,
                                 name_location="middle",
                                 type_="category",
                                 boundary_gap=False,
                                 splitline_opts=opts.SplitLineOpts(is_show=True)),
        yaxis_opts=opts.AxisOpts(name="Time(ms)",
                                 name_gap=30,
                                 name_location="middle",
                                 name_rotate="90",
                                 splitline_opts=opts.SplitLineOpts(is_show=True), )
    )
    line.add_xaxis(xaxis_data=number_items_list)
    line.add_yaxis(series_name=sort_name, y_axis=consumedTime)
    make_snapshot(snapshot, line.render(), png_name, is_remove_html=True)
    print("\n"+png_name+" maked done\n")

def run_(algo,doc_path="./doc_report/（3） 冒泡排序.docx"):
    print("\n")
    number_items_list = ["1000", "2000", "3000", "4000", "5000", "6000", "7000", "8000", "9000", "10000"]
    time_list = runTest(algo)
    i=0
    result_list=[]
    for time in time_list:
        str_= str (number_items_list[i])+"  "+str (time)
        print(str_)
        result_list.append(str_)
        i=i+1
    png_maker(time_list, algo.__name__)
#     todo: using StringIO write into docx
    doc=doc_control.doc_control(doc_path=doc_path,algo=algo)
    doc.add_algo_title()
    doc.add_algo_code()
    doc.add_code_result(result_set=result_list)
    doc.add_png()


if __name__ == '__main__':
    run_(sorts.quick_sort)





